package org.otarriinae.security.base.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.otarriinae.security.base.constant.StringsConstant;
import org.otarriinae.security.base.model.TokenUserDetails;
import org.otarriinae.security.base.utils.SecurityUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author xj
 * @since 1.0
 */
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {


    private final RedisTemplate<String, String> valueOperations;

    public TokenAuthenticationFilter(RedisTemplate<String, String> valueOperations) {
        this.valueOperations = valueOperations;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {

        String authToken = SecurityUtils.getToken(request);

        if (!StringUtils.isEmpty(authToken)) {
            String userString = valueOperations.opsForValue().get(StringsConstant.getRedisToken(authToken));
            if (!StringUtils.isEmpty(userString)) {
                TokenUserDetails userDetails = JSON.parseObject(userString, TokenUserDetails.class);
                if (Objects.nonNull(userDetails) &&
                        Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {

                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                            request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }

        filterChain.doFilter(request, response);
    }


}
